﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.IO;
using LibrarySync2.Common.Enum;
using LibrarySync2.Common.Extensions;
using LibrarySync2.Business.FileSystem;
using LibrarySync2.Common.Event;
using LibrarySync2.Common.Xml;

namespace LibrarySync2.Business.Worker
{
    public class LibraryAnalyzer
    {
        private readonly BackgroundWorker _fileInfoRetriever;
        private DirectoryInfo _mediaSourceDirectory;
        private FileInfo _libraryFilePath;
        public event EventHandler<LibraryAnalysisEventArgs> LibraryAnalysisUpdate;

        public bool Running { get; private set; }

        public LibraryAnalyzer(string mediaSourceDirectory, string libraryFilePath)
        {
            if (string.IsNullOrEmpty(mediaSourceDirectory))
                throw new ArgumentNullException("mediaSourceDirectory");
            if (string.IsNullOrEmpty(libraryFilePath))
                throw new ArgumentNullException("libraryFilePath");
            _mediaSourceDirectory = new DirectoryInfo(mediaSourceDirectory);
            if (!_mediaSourceDirectory.Exists)
                throw new ArgumentException("Media source directory does not exist.");

            _fileInfoRetriever = new BackgroundWorker();
            _fileInfoRetriever.DoWork += new DoWorkEventHandler(_fileInfoRetriever_DoWork);
            _fileInfoRetriever.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_fileInfoRetriever_RunWorkerCompleted);
            _fileInfoRetriever.WorkerSupportsCancellation = true;

            _libraryFilePath = new FileInfo(libraryFilePath);
            if (_libraryFilePath.Exists)
                _libraryFilePath.Delete();
        }

        public void Start()
        {
            _fileInfoRetriever.RunWorkerAsync();
        }

        public void Cancel()
        {
            _fileInfoRetriever.CancelAsync();
        }

        #region BackgroungWorker Events

        protected void _fileInfoRetriever_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Running = true;

            this.LibraryAnalysisUpdate.Raise(this, new LibraryAnalysisEventArgs(LibraryAnalysisStatusType.BuildingFileList, 0, 0));
            Library library = new Library(_mediaSourceDirectory);
            this.LibraryAnalysisUpdate.Raise(this, new LibraryAnalysisEventArgs(LibraryAnalysisStatusType.SerializingResults, 0, 0));
            library.Serialize(this._libraryFilePath);
        }

        protected void _fileInfoRetriever_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LibraryAnalysisUpdate.Raise(this, new LibraryAnalysisEventArgs(
                e.Cancelled ? LibraryAnalysisStatusType.Cancelled : LibraryAnalysisStatusType.Complete,
                0, 0));

            this.Running = false;
        }

        #endregion BackgroungWorker Events
    }
}
